package com.sdkj.fixed.asset.system.service;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.sdkj.fixed.asset.api.login.out_vo.CompanyBaseListResult;
import com.sdkj.fixed.asset.api.login.out_vo.LoginUserResultPC;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.api.system.in_vo.EditState;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.core.RoleType;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.ObjectUtil;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.pojo.DeptImportManagement;
import com.sdkj.fixed.asset.pojo.OrgImportManagement;
import com.sdkj.fixed.asset.pojo.system.*;
import com.sdkj.fixed.asset.system.mapper.*;
import com.sdkj.fixed.asset.system.util.CacheUtil;
import com.sdkj.fixed.asset.system.util.OrgImportVerify;
import com.sdkj.fixed.asset.system.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName OrgService
 * @Description TODO
 * @Author 张欣
 * @Date 2020/7/20 14:48
 */
@Service
public class OrgService extends BaseService<OrgManagement> {
    private static Logger log = LoggerFactory.getLogger(OrgService.class);
    @Value("${sys.add.org.life.time}")
    private Integer sysAddOrgLifeTime;
    @Autowired
    private OrgManagementMapper orgMapper;
    @Autowired
    private UserManagementMapper userMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleManagementMapper roleManagementMapper;
    @Autowired
    private RoleAndMenuMapper roleAndMenuMapper;
    @Autowired
    private AuthActionMapper authActionMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private OrgImportVerify orgImportVerify;
    @Autowired
    private UsageManagementMapper usageManagementMapper;

    @Override
    public BaseMapper getMapper() {
        return orgMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    public void addOrg(OrgManagement entity,String companyId){
        //校验唯一性,顶级整库唯一，子级公司下唯一
        validateCompanyCode(entity.getCode(),"",entity.getPid(),companyId);

        //如果是部门父节点不能为空
        if(entity.getType()==2 && StrUtil.isBlank(entity.getPid())){
            throw new LogicException("必须选择公司");
        }
        if(StrUtil.isBlank(entity.getPid())){
            entity.setPid("NONE");
        }else{
            if(orgMapper.selectByPrimaryKey(entity.getPid()).getTreecode().length() == 263){
                throw new LogicException("园区最多可以添加8层");
            }
        }
        entity.setTreecode("");
        entity.setCtime(DateUtil.now());
        entity.setEtime(DateUtil.now());
        entity.setState(1);
        orgMapper.insertSelective(entity);

        //初始化树
        innitTreeCode(entity);
        if(entity.getPid().equals("NONE")){
            //初始化角色
            initRole(entity.getCuser(), entity.getId());
            //新增公司使用情况
            initUsageConmpany(entity);
        }
        if(entity.getType() == 1){
            //保存缓存信息
            Map<String, Integer> parkInfo = (Map<String, Integer>) redisUtil.get("orgInfo");
            if(parkInfo == null){
                parkInfo = new HashMap<String, Integer>();
            }
            parkInfo.put(entity.getId(),1);
            redisUtil.set("orgInfo",parkInfo);
        }
        if (cacheUtil.getUserRoleByKey("PC_" + entity.getCuser()).contains(RoleType.SYSADMIN.getRoleType())) {
            List<OrgManagement> allOrg = getAllOrg("", true, true);
            if(allOrg.size() == 1){
                //修改redis登录信息
                LoginUserResultPC redis = (LoginUserResultPC)redisUtil.get("PC_" + entity.getCuser());
                CompanyBaseListResult company = new CompanyBaseListResult();
                company.setCompanyId(entity.getId());
                company.setCompanyName(entity.getName());
                company.setParentId(entity.getPid());
                ArrayList<CompanyBaseListResult> companyList = new ArrayList<>();
                companyList.add(company);
                redis.setCompanys(companyList);
                redisUtil.set("PC_" + entity.getCuser(),redis,redisUtil.getExpire("PC_" + entity.getCuser()));
            }

        }

    }

    //新增公司使用情况
    private void initUsageConmpany(OrgManagement entity){
        UsageManagement usageManagement = new UsageManagement();
        usageManagement.setCompanyId(entity.getId());
        usageManagement.setNumber("无限制");
        usageManagement.setType(3);
        usageManagement.setCuser("管理员新增");
        usageManagement.setEuser("管理员新增");
        usageManagement.setCtime(DateUtil.now());
        usageManagement.setEtime(DateUtil.now());
        usageManagement.setDate(TimeTool.getBeforMonth(sysAddOrgLifeTime).substring(0,10));
        usageManagementMapper.insertSelective(usageManagement);
    }

    /**
     * 初始化treecode
     * @param org
     * @return
     */
    private OrgManagement innitTreeCode(OrgManagement org)  {
        String parentId = org.getPid();
        if (parentId.equals("NONE")) {
            org.setTreecode(org.getId());
        } else {
            org.setTreecode(orgMapper.selectByPrimaryKey(parentId).getTreecode() + ","+org.getId());
        }
        orgMapper.updateByPrimaryKeySelective(org);
        return org;
    }
    //初始化角色
    public RoleManagement initRole(String userId, String companyId) {
        RoleManagement role = new RoleManagement();
        role.setIsDefault(2);
        role.setLevel("2");
        role.setCuser(userId);
        role.setEuser(userId);
        role.setComments("初始化角色请勿删除");
        role.setName("管理员");
        role.setOrgId(companyId);
        roleService.addRole(role);
        //初始化角色菜单
        initRoleMenu(role.getId());
        return role;
    }

    /**
     * 初始化角色菜单
     * @param roleId
     */
    private void initRoleMenu(String roleId){
        //查询所有角色初始化可用菜单
        Example example = new Example(AuthAction.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("state",1);
        criteria.andEqualTo("isInitUse",1);
        List<AuthAction> roleManagements = authActionMapper.selectByExample(example);
        List<String> ids = roleManagements.stream().map(AuthAction::getId).collect(Collectors.toList());
        List<RoleAndMenu> entitys = new ArrayList<RoleAndMenu>();
        for(String id : ids){
            RoleAndMenu roleAndMenu = new RoleAndMenu();
            roleAndMenu.setAuthId(id);
            roleAndMenu.setRoleId(roleId);
            roleAndMenuMapper.insertSelective(roleAndMenu);
        }

    }

    /**
     * 校验公司code
     * @param code
     * @param id
     * @param pid
     * @param companyId
     */
    public void validateCompanyCode(String code,String id,String pid,String companyId){
        Example example = new Example(OrgManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("code",code);
        //criteria.andEqualTo("type",1);
        if(StrUtil.isNotBlank(id)){
            criteria.andNotEqualTo("id",id);
        }
        if(StrUtil.isNotBlank(pid)){
            //如果有父级,公司下唯一
            criteria.andCondition(" (treecode like '"+companyId +"%' or id = '"+companyId+"')");
        }else{
            //所有父级中唯一
            criteria.andEqualTo("pid","NONE");
        }
        List<OrgManagement> orgManagements = orgMapper.selectByExample(example);
        if(orgManagements.size() > 0){
            throw new LogicException("组织架构编码不能重复【"+code+"】");
        }
    }

    /**
     * 修改机构
     * @param entity
     * @param companyId
     */
    public void editOrg(OrgManagement entity,String companyId){
        OrgManagement orgManagement = orgMapper.selectByPrimaryKey(entity.getId());
        if(orgManagement == null ){
            throw new LogicException("组织架构不存在");
        }
        if(orgManagement.getState() == 2){
            throw new LogicException("组织架构已禁用不可修改");
        }
        if(StrUtil.isBlank(entity.getPid())){
            entity.setPid("NONE");
        }
        if(!orgManagement.getPid().equals(entity.getPid())){
            throw new LogicException("不可以修改父级");
        }
        //校验唯一性,顶级整库唯一，子级公司下唯一
        validateCompanyCode(entity.getCode(),entity.getId(),entity.getPid(),companyId);

        //如果是部门父节点不能为空
        if(entity.getType()==2 && StrUtil.isBlank(entity.getPid())){
            throw new LogicException("必须选择公司");
        }
        orgManagement.setName(entity.getName());
        orgManagement.setCode(entity.getCode());
        orgManagement.setEtime(DateUtil.now());
        orgMapper.updateByPrimaryKeySelective(orgManagement);
    }

    /**
     * 禁用或启用
     * @param editState
     * @param loginUserId
     */
    public void forbiddenOrOrgEnable(EditState editState,String loginUserId){
        OrgManagement orgManagement = orgMapper.selectByPrimaryKey(editState.getId());
        if(orgManagement == null){
            throw new LogicException("组织机构不存在");
        }
        //查询所有子节点
        Example example = new Example(OrgManagement.class);
        Example.Criteria criteria = example.createCriteria();
        if(editState.getState() == 2){
            criteria.andEqualTo("state",1);
        }
        criteria.andLike("treecode",orgManagement.getTreecode()+"%");

        List<OrgManagement> orgManagements = orgMapper.selectByExample(example);
        for(OrgManagement org : orgManagements){
            org.setEuser(loginUserId);
            org.setEtime(DateUtil.now());
            org.setState(editState.getState());
            orgMapper.updateByPrimaryKeySelective(org);
        }
        //保存缓存信息
        Map<String, Integer> parkInfo = (Map<String, Integer>) redisUtil.get("orgInfo");
        if(parkInfo == null){
            parkInfo = new HashMap<String, Integer>();
        }
        for(OrgManagement org:orgManagements ){
            parkInfo.put(org.getId(),editState.getState());
        }

        redisUtil.set("orgInfo",parkInfo);
    }

    /**
     * 获取所有机构
     * @param companyId
     * @param isAdmin
     * @param isEnable
     * @return
     */
    public List<OrgManagement> getAllOrg(String companyId,boolean isAdmin,boolean isEnable){
        Example example = new Example(OrgManagement.class);
        Example.Criteria criteria = example.createCriteria();
        if(isEnable){
            criteria.andEqualTo("state","1");
        }
        if(isAdmin){
            criteria.andEqualTo("pid","NONE");
        }else{
            criteria.andLike("treecode",companyId+"%");
        }
        return orgMapper.selectByExample(example);
    }
    /**
     * 获取所有启用公司
     * @param companyId
     * @param isAdmin
     * @param
     * @return
     */
    public List<OrgManagement> getEnableCompany(String companyId,boolean isAdmin){
        Example example = new Example(OrgManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("state",1);
        criteria.andEqualTo("type",1);
        if(isAdmin){
            criteria.andEqualTo("pid","NONE");
        }else{
            criteria.andLike("treecode",companyId+"%");
        }
        return orgMapper.selectByExample(example);
    }

    /**
     * 获取当前登录用户权限下所有启用公司 20210423修改
     *
     * @param companyId
     * @param isAdmin
     * @param
     * @return
     */
    public List<OrgManagement> getAuthEnableCompany(String companyId, boolean isAdmin, String loginUserId) {
        Example example = new Example(OrgManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("state", 1);
        criteria.andEqualTo("type", 1);
        if (isAdmin) {
            return new ArrayList<>();
        }
        Example example2 = new Example(UserManagement.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("id", loginUserId);
        List<UserManagement> userManagements = userMapper.selectByExample(example2);
        if (userManagements.size() == 0) {
            throw new LogicException("当前登录用户不存在");
        }
        if (userManagements.get(0).getDataIsAll() == 1) {
            criteria.andLike("treecode", companyId + "%");
            return orgMapper.selectByExample(example);
        }
        List<OrgManagement> authEnableCompany = orgMapper.getAuthEnableCompany(loginUserId);


        //判断是否为公司,找到公司
        for (OrgManagement orgpid : authEnableCompany) {
            if (orgpid.getType() != 1) {
                OrgManagement orgManagement = orgMapper.getPid(orgpid.getPid());
                orgpid.setId(orgManagement.getId());
                orgpid.setName(orgManagement.getName());
                orgpid.setPid(orgManagement.getPid());
                orgpid.setCode(orgManagement.getCode());
                orgpid.setType(orgManagement.getType());
            }
        }

        //判断是否为顶级
        for (OrgManagement company : authEnableCompany) {
            Boolean flag = false;
            for (OrgManagement company1 : authEnableCompany) {
                if (company.getPid().equals(company1.getId())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                company.setPid("");
            }
        }
        //list去重
        List<OrgManagement> listWithoutDuplicates = authEnableCompany.stream().collect(Collectors.collectingAndThen
                (Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(OrgManagement::getId))), ArrayList::new));
        return listWithoutDuplicates;
    }


    /**
     * 获取当前登录用户权限下所有启用公司
     *
     * @param companyId
     * @param isAdmin
     * @param
     * @return
     */
    public List<OrgManagement> getAuthEnableCompany1(String companyId, boolean isAdmin, String loginUserId) {
        Example example = new Example(OrgManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("state", 1);
        criteria.andEqualTo("type", 1);
        if (isAdmin) {
            return new ArrayList<>();
        }
        Example example2 = new Example(UserManagement.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("id", loginUserId);
        List<UserManagement> userManagements = userMapper.selectByExample(example2);
        if (userManagements.size() == 0) {
            throw new LogicException("当前登录用户不存在");
        }
        if (userManagements.get(0).getDataIsAll() == 1) {
            criteria.andLike("treecode", companyId + "%");
            return orgMapper.selectByExample(example);
        }
        List<OrgManagement> authEnableCompany = orgMapper.getAuthEnableCompany(loginUserId);

        for (OrgManagement company : authEnableCompany) {
            Boolean flag = false;
            for (OrgManagement company1 : authEnableCompany) {
                if (company.getPid().equals(company1.getId())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                company.setPid("");
            }
        }

        return authEnableCompany;
    }

    /**
     * 获取当前登录用户权限下所有启用公司
     *
     * @param companyId
     * @param isAdmin
     * @param
     * @return
     */
    public List<OrgManagement> getAuthOrg(String companyId, boolean isAdmin, String loginUserId) {
        Example example = new Example(OrgManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("state", 1);
        if (isAdmin) {
            return new ArrayList<>();
        }
        Example example2 = new Example(UserManagement.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("id", loginUserId);
        List<UserManagement> userManagements = userMapper.selectByExample(example2);
        if (userManagements.size() == 0) {
            throw new LogicException("当前登录用户不存在");
        }
        if (userManagements.get(0).getDataIsAll() == 1) {
            criteria.andLike("treecode", companyId + "%");
            return orgMapper.selectByExample(example);
        }
        List<OrgManagement> authEnableOrg = orgMapper.getAuthEnableOrg(loginUserId);
        for (OrgManagement org : authEnableOrg) {
            Boolean flag = false;
            for (OrgManagement org1 : authEnableOrg) {
                if (org.getPid().equals(org1.getId())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                org.setPid("");
            }
        }

        return authEnableOrg;
    }
    /**
     * 获取公司下启用状态的部门
     * @param companyId
     * @return
     */
    public List<OrgManagement> getEnableDeptByCompanyId(String companyId){

        Example example = new Example(OrgManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("state",1);
        criteria.andEqualTo("type",2);
        criteria.andEqualTo("pid",companyId);
        List<OrgManagement> depts = orgMapper.selectByExample(example);
        List<OrgManagement> deptResult = new ArrayList<>();
        for(OrgManagement dept : depts){
            if(orgMapper.selectByPrimaryKey(dept.getPid()).getType() == 1){
                dept.setPid("");
            }
        }
        deptResult.addAll(depts);
        for(OrgManagement dept : depts){
            Example example2 = new Example(OrgManagement.class);
            Example.Criteria criteria2 = example2.createCriteria();
            criteria2.andEqualTo("state",1);
            criteria2.andEqualTo("type",2);
            criteria2.andNotEqualTo("id",dept.getId());
            criteria2.andLike("treecode",dept.getTreecode()+"%");
            deptResult.addAll(orgMapper.selectByExample(example2)) ;
        }

        return deptResult;
    }
    /**
     * 获取权限公司下启用状态的部门
     * @param companyId
     * @return
     */
    public List<OrgManagement> getAuthEnableDeptByCompanyId(String companyId,String loginUserId){
        Example example2 = new Example(UserManagement.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("id",loginUserId);
        List<UserManagement> userManagements = userMapper.selectByExample(example2);
        if(userManagements.size() == 0){
            throw new LogicException("当前登录用户不存在");
        }
        List<OrgManagement> depts = new ArrayList<>();

        Example example = new Example(OrgManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("state",1);
        criteria.andEqualTo("type",2);
        criteria.andEqualTo("pid",companyId);
        depts = orgMapper.selectByExample(example);
        for(OrgManagement dept : depts){
            if(orgMapper.selectByPrimaryKey(dept.getPid()).getType() == 1){
                dept.setPid("");
            }
        }
        List<OrgManagement> deptResult = new ArrayList<>();
        deptResult.addAll(depts);
        for(OrgManagement dept : depts){
            Example example3 = new Example(OrgManagement.class);
            Example.Criteria criteria3 = example3.createCriteria();
            criteria3.andEqualTo("state",1);
            criteria3.andEqualTo("type",2);
            criteria3.andNotEqualTo("id",dept.getId());
            criteria3.andLike("treecode",dept.getTreecode()+"%");
            deptResult.addAll(orgMapper.selectByExample(example3)) ;
        }
        if(userManagements.get(0).getDataIsAll() == 2){
            List<OrgManagement> authEnableDeptByCompanyId = orgMapper.getAuthEnableDeptByCompanyId(loginUserId,companyId);
//            for(OrgManagement deptTotal : deptResult){
//                boolean flag = true;
//                for(OrgManagement dept : authEnableDeptByCompanyId){
//                    if(deptTotal.getId().equals(dept.getId())){
//                        flag = false;
//                        break;
//                    }
//                }
//                if(flag){
//                    deptResult.remove(deptTotal);
//                }
//            }
            for (int i = 0; i < deptResult.size(); i++) {
                boolean flag = true;
                for(OrgManagement dept : authEnableDeptByCompanyId){
                    if(deptResult.get(i).getId().equals(dept.getId())){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    deptResult.remove(i);
                    i--;//删除后，索引要减一，否则报错java.util.ConcurrentModificationException: null
                }
            }

        }
        for(OrgManagement company : deptResult){
            Boolean flag = false;
            for(OrgManagement company1 : deptResult){
                if(company.getPid().equals(company1.getId())){
                    flag = true;
                    break;
                }
            }
            if(!flag){
                company.setPid("");
            }
        }

        return deptResult;
    }
    /**
     * 新增导入的公司
     * @param file
     * @param loginUser
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertImportOrg(MultipartFile file, LoginUser loginUser) throws Exception {
        ExcelImportResult<OrgImportManagement> result = handCompanyExcel(file);
        List<OrgImportManagement> list = result.getList();
        if(isAdmin()){
            //如果是超级管理员，只能新增根节点，直接新增
            insertCompanyForImportAdmin(list,loginUser.getUserId());
            return;
        }
        //查找导入excel中最顶级的公司
        List<OrgImportManagement> topList = new ArrayList<>();
        for(OrgImportManagement impottEntity : list ){
            boolean flag = true;
            for(OrgImportManagement impottEntity2 : list ){
                if(impottEntity.getPcode().equals(impottEntity2.getCode())){
                    flag = false;
                    break;
                }

            }
            if(flag){
                topList.add(impottEntity);
            }
        }
        list.removeAll(topList);
        String topCompanyId = loginUser.getCompanys().get(0).getCompanyId();
        addCompanyforNotAdmin(loginUser, topCompanyId,topList,list);

    }
    //非管理员新增公司
    private void addCompanyforNotAdmin(LoginUser loginUser, String topCompanyId,List<OrgImportManagement> topList,List<OrgImportManagement> list) {
        for(OrgImportManagement company : topList) {
            //查找其父节点是否存在
            List<OrgManagement> orgByCode = getOrgByCode(company.getPcode(), 1, "",topCompanyId);
            if (orgByCode.size() == 0) {
                throw new LogicException("公司【" + company.getPcode() + "】不存在");
            }
            //查询是否存在
            Example example = new Example(OrgManagement.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("code", company.getCode());
            criteria.andEqualTo("type", 1);
            criteria.andLike("treecode", topCompanyId + "%");
            List<OrgManagement> orgManagements = orgMapper.selectByExample(example);
            OrgManagement insertEntity = null;
            if (orgManagements.size() == 0) {
                //新增
                 insertEntity = addCompany(loginUser.getUserId(), company, orgByCode.get(0).getId());

            }else if (!(orgManagements.get(0)).getPid().equals(orgByCode.get(0).getId())) {
                log.info("导入公司错误数据：父级不同【" + company.getName() + "】");
            }else{
                insertEntity = orgManagements.get(0);
                //修改
                insertEntity.setEuser(loginUser.getUserId());
                insertEntity.setEtime(DateUtil.now());
                insertEntity.setName(company.getName());
                orgMapper.updateByPrimaryKeySelective(insertEntity);
            }

            //查找其子公司
            findChildren(list,insertEntity,topCompanyId, loginUser.getUserId());
        }
    }
    //新增其子项
    private void findChildren(List<OrgImportManagement> list,OrgManagement pCompany,String companyId,String loginUserId){
        String pid = pCompany.getId();
        String pCode = pCompany.getCode();
        List<OrgImportManagement> children = new ArrayList<>();
        for(OrgImportManagement entity : list){
            if(entity.getPcode().equals(pCode)){
                children.add(entity);
            }
        }
        list.removeAll(children);
        //新增
        for(OrgImportManagement entity : children){
            //校验code是否存在，存在抛异常
            //查询是否存在
            Example example = new Example(OrgManagement.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("code", entity.getCode());
            criteria.andEqualTo("type", 1);
            criteria.andLike("treecode", companyId + "%");
            List<OrgManagement> orgManagements = orgMapper.selectByExample(example);
            OrgManagement insertEntity = null;
            if (orgManagements.size() == 0) {
                //新增
                 insertEntity = addCompany(loginUserId, entity, pid);

            }else if (!(insertEntity = orgManagements.get(0)).getPid().equals(pid)) {
                log.info("导入公司错误数据：父级不同【" + entity.getName() + "】");
            }else{
                insertEntity = orgManagements.get(0);
                //修改
                insertEntity.setEuser(loginUserId);
                insertEntity.setEtime(DateUtil.now());
                insertEntity.setName(entity.getName());
                orgMapper.updateByPrimaryKeySelective(insertEntity);
            }
            //查找其子公司
            findChildren(list,insertEntity,companyId, loginUserId);
        }
    }
    /**
     * 管理员的新增方法
     * @param list
     * @param loginUser
     */
    private void insertCompanyForImportAdmin(List<OrgImportManagement> list,String loginUser) {
        for(OrgImportManagement impottEntity : list ){
            //查询机构是否存在
            Example example  = new Example(OrgManagement.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("code",impottEntity.getCode());
            criteria.andEqualTo("type",1);
            criteria.andEqualTo("pid","NONE");
            List<OrgManagement> orgManagements = orgMapper.selectByExample(example);
            if(orgManagements.size() == 0){
                addCompany(loginUser, impottEntity,"NONE");

            }else{
                OrgManagement orgManagement = orgManagements.get(0);
                orgManagement.setName(impottEntity.getName());
                orgManagement.setEtime(DateUtil.now());
                orgManagement.setEuser(loginUser);
                orgMapper.updateByPrimaryKeySelective(orgManagement);
            }
        }
    }
    //新增公司。导入使用
    private OrgManagement addCompany(String loginUser, OrgImportManagement impottEntity,String pid) {
        OrgManagement orgManagement = new OrgManagement();
        orgManagement.setName(impottEntity.getName());
        orgManagement.setCode(impottEntity.getCode());
        orgManagement.setEtime(DateUtil.now());
        orgManagement.setEuser(loginUser);
        orgManagement.setCuser(loginUser);
        orgManagement.setCtime(DateUtil.now());
        orgManagement.setState(1);
        orgManagement.setType(1);
        orgManagement.setPid(pid);
        orgManagement.setTreecode("");
        orgMapper.insertSelective(orgManagement);
        //初始化树
        innitTreeCode(orgManagement);
        if(pid.equals("NONE")){
            //初始化角色
            initRole(orgManagement.getCuser(), orgManagement.getId());
        }

        //保存缓存信息
        Map<String, Integer> parkInfo = (Map<String, Integer>) redisUtil.get("orgInfo");
        if(parkInfo == null){
            parkInfo = new HashMap<String, Integer>();
        }
        parkInfo.put(orgManagement.getId(),1);
        redisUtil.set("orgInfo",parkInfo);
        return orgManagement;
    }

    /**
     * 处理导入公司文件
     * @param file
     * @return
     * @throws Exception
     */
    private ExcelImportResult<OrgImportManagement> handCompanyExcel(MultipartFile file) throws Exception {
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        // 需要验证
        importParams.setNeedVerfiy(true);
        importParams.setVerifyHandler(orgImportVerify);
        ExcelImportResult<OrgImportManagement> result = ExcelImportUtil.importExcelMore(file.getInputStream(), OrgImportManagement.class,
                importParams);
        //校验是否有错误
        List<OrgImportManagement> failList = result.getFailList();
        for (OrgImportManagement orgImportManagement : failList) {
            if (ObjectUtil.checkObjAllFieldsIsNull(orgImportManagement)) {
                failList.remove(orgImportManagement);
            }
        }
        if(failList.size() > 0){
            throw new LogicException( "第" + (failList.get(0).getRowNum()+1)  + "行错误：" + failList.get(0).getErrorMsg());
        }
        return result;
    }
    private List<OrgManagement> getOrgByCode(String code,int type,String pid,String topCompany) {
        Example example  = new Example(OrgManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("code",code);

        criteria.andEqualTo("state",1);
        criteria.andLike("treecode",topCompany+"%");
        if(type == 1){
            criteria.andEqualTo("type",type);
        }
        return  orgMapper.selectByExample(example);
    }
    public boolean isAdmin(){
        String token = request.getHeader("token");
        return cacheUtil.getUserRole(token).contains(RoleType.SYSADMIN.getRoleType());
    }

    /**
     * 导入部门
     * @param file
     * @param loginUser
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertImportDept(MultipartFile file, LoginUser loginUser) throws Exception {
        ExcelImportResult<DeptImportManagement> result = handDeptExcel(file);
        List<DeptImportManagement> list = result.getList();
        if(isAdmin()){
            //如果是超级管理员，只能新增根节点，直接新增
            throw new LogicException("超级管理员不能操作该按钮");
        }
        //查找导入excel中最顶级的部门
        List<DeptImportManagement> topList = new ArrayList<>();
        for(DeptImportManagement impottEntity : list ){
            boolean flag = true;
            for(DeptImportManagement impottEntity2 : list ){
                if(impottEntity.getPcode().equals(impottEntity2.getCode())){
                    flag = false;
                    break;
                }
            }
            if(flag){
                topList.add(impottEntity);
            }
        }
        list.removeAll(topList);
        String companyId = loginUser.getCompanys().get(0).getCompanyId();
        addDeptforNotAdmin(loginUser, companyId,topList,list);

    }
    /**
     * 处理导入公司文件
     * @param file
     * @return
     * @throws Exception
     */
    private ExcelImportResult<DeptImportManagement> handDeptExcel(MultipartFile file) throws Exception {
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        // 需要验证
        importParams.setNeedVerfiy(true);
        ExcelImportResult<DeptImportManagement> result = ExcelImportUtil.importExcelMore(file.getInputStream(), DeptImportManagement.class,
                importParams);
        //校验是否有错误
        List<DeptImportManagement> failList = result.getFailList();
        for (DeptImportManagement deptImportManagement : failList) {
            if (ObjectUtil.checkObjAllFieldsIsNull(deptImportManagement)) {
                failList.remove(deptImportManagement);
            }
        }
        if(failList.size() > 0){
            throw new LogicException( "第" + (failList.get(0).getRowNum()+1) + "行错误：" + failList.get(0).getErrorMsg());
        }
        return result;
    }
    //非管理员新增公司
    private void addDeptforNotAdmin(LoginUser loginUser, String companyId,List<DeptImportManagement> topList,List<DeptImportManagement> list) {
        for(DeptImportManagement dept : topList) {
            //查找其父节点是否存在
            List<OrgManagement> orgByCode = getOrgByCode(dept.getPcode(), 2, "",companyId);
            if (orgByCode.size() == 0 || (!orgByCode.get(0).getTreecode().contains(companyId))) {
                throw new LogicException("上级部门或公司【" + dept.getPcode() + "】不存在");
            }
            //查询是否存在
            Example example = new Example(OrgManagement.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("code", dept.getCode());
            criteria.andEqualTo("type", 2);
            criteria.andLike("treecode", companyId + "%");
            List<OrgManagement> orgManagements = orgMapper.selectByExample(example);
            OrgManagement insertEntity = null;
            if (orgManagements.size() == 0) {
                //新增
                insertEntity = addDept(loginUser.getUserId(), dept, orgByCode.get(0).getId());

            }else if (!(insertEntity = orgManagements.get(0)).getPid().equals(orgByCode.get(0).getId())) {
                log.info("导入部门错误数据：父级不同【" + dept.getName() + "】");
            }else{
                insertEntity = orgManagements.get(0);
                //修改
                insertEntity.setEuser(loginUser.getUserId());
                insertEntity.setEtime(DateUtil.now());
                insertEntity.setName(dept.getName());
                orgMapper.updateByPrimaryKeySelective(insertEntity);
            }

            //查找其子部门
            findChildrenDept(list,insertEntity,companyId, loginUser.getUserId());
        }
    }
    //新增部门。导入使用
    private OrgManagement addDept(String loginUser, DeptImportManagement impottEntity,String pid) {
        OrgManagement orgManagement = new OrgManagement();
        orgManagement.setName(impottEntity.getName());
        orgManagement.setCode(impottEntity.getCode());
        orgManagement.setEtime(DateUtil.now());
        orgManagement.setEuser(loginUser);
        orgManagement.setCuser(loginUser);
        orgManagement.setCtime(DateUtil.now());
        orgManagement.setState(1);
        orgManagement.setType(2);
        orgManagement.setPid(pid);
        orgManagement.setTreecode("");
        orgMapper.insertSelective(orgManagement);
        innitTreeCode(orgManagement);
        return orgManagement;
    }
    //新增其子项
    private void findChildrenDept(List<DeptImportManagement> list,OrgManagement pCompany,String companyId,String loginUserId){
        String pid = pCompany.getId();
        String pCode = pCompany.getCode();
        List<DeptImportManagement> children = new ArrayList<>();
        for(DeptImportManagement entity : list){
            if(entity.getPcode().equals(pCode)){
                children.add(entity);
            }
        }
        list.removeAll(children);
        //新增
        for(DeptImportManagement entity : children){
            //校验code是否存在，存在抛异常
            //查询是否存在
            Example example = new Example(OrgManagement.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("code", entity.getCode());
            criteria.andEqualTo("type", 2);
            criteria.andLike("treecode", companyId + "%");
            List<OrgManagement> orgManagements = orgMapper.selectByExample(example);
            OrgManagement insertEntity = null;
            if (orgManagements.size() == 0) {
                //新增
                insertEntity = addDept(loginUserId, entity, pid);

            }else if (!(insertEntity = orgManagements.get(0)).getPid().equals(pid)) {
                log.info("导入部门错误数据：父级不同【" + entity.getName() + "】");
            }else{
                insertEntity = orgManagements.get(0);
                //修改
                insertEntity.setEuser(loginUserId);
                insertEntity.setEtime(DateUtil.now());
                insertEntity.setName(entity.getName());
                orgMapper.updateByPrimaryKeySelective(insertEntity);
            }
            //查找其子公司
            findChildrenDept(list,insertEntity,companyId, loginUserId);
        }
    }
}

